package com.epro.dx.activity.coupon.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.epro.dx.R;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.LandingPageActivity;
import com.epro.dx.activity.ProductListActivity;
import com.epro.dx.activity.coupon.adapter.MyCouponListAdapter;
import com.epro.dx.fragment.BaseLoadAndEmptyDataFragment;
import com.epro.dx.listenner.OnCouponExpiredListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.CouponActiveModel;
import com.weipu.common.facade.model.CouponModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;

import java.util.ArrayList;
import java.util.List;
@SuppressLint("ValidFragment")
public class MyCouponFragment extends BaseLoadAndEmptyDataFragment implements OnItemLongClickListener, OnItemClickListener {
	
	private RelativeLayout emptyPage;//无数据布局
	private RelativeLayout haveDataPage;//有数据布局
	private View rootView;//根布局
	private PullToRefreshListView listView;//coupon列表
	public int pageIndex = 0;//查询起始页
	private int pageSize = 10;//每页查询数据条数
	private ArrayList<CouponModel> couponList = new ArrayList<CouponModel>();
	private ArrayList<CouponModel> coupons;//用于存储一次查询到的Coupon集合
	private MyCouponListAdapter myCouponListAdapter;//Coupon列表数据适配器
	private int currentPage;
	private boolean isLoading = false;
	private boolean isPullUp = false;
//	private ProgressBar progressLoad;
	
	public MyCouponFragment(int currentPage){
		this.currentPage = currentPage;
	}
	public MyCouponFragment(){}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(savedInstanceState!=null){
			this.currentPage = savedInstanceState.getInt("CurrentPage");
		}
		if(rootView == null){
//			rootView = View.inflate(getActivity(),R.layout.fragment_mycoupon , null);
		    rootView=inflate(R.layout.fragment_coupon);
		    initView();
		    initEvent();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if(parent!=null){
			parent.removeView(rootView);
		}
		return rootView;
	}
	@Override
	public void onSaveInstanceState(Bundle outState) {
//		super.onSaveInstanceState(outState);
		outState.putInt("CurrentPage", currentPage);
	}
	/**
	 * @param currentPage 页面编号
	 * 设置当前的页面编号
	 */
	public void setCurrentPage(int currentPage){
		this.currentPage = currentPage;
	}
	
	/**
	 * 加载数据
	 */
	public void initData() {
		if(currentPage == 1){
			// 连接接服务器获取数据
			AsyncTaskUtil.executeTask(new GetMyCouponList());
		}
	}
	
	/**
	 * 初始化UI
	 */
	private void initView() {
		listView = (PullToRefreshListView) rootView.findViewById(R.id.coupon_couponlist);
//		progressLoad=(ProgressBar) rootView.findViewById(R.id.loading_progress);
		haveDataPage = (RelativeLayout) rootView.findViewById(R.id.coupon_page_havedata);
		myCouponListAdapter = new MyCouponListAdapter(getActivity(),couponList);
		listView.setAdapter(myCouponListAdapter);
		listView.setMode(Mode.BOTH);
		//屏蔽默认的点击效果
		listView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		listView.getRefreshableView().setCacheColorHint(getResources().getColor(R.color.transparent));
	}
	
	@Override
	public void onResume() {
		if(currentPage == 1){
			initData();
		}
		super.onResume();
	}
	
	/**
	 * 加载事件
	 */
	private void initEvent() {
		myCouponListAdapter.setOnCouponExpiredListenner(new OnCouponExpiredListenner(){
			public void onExpired(int position) {
				if(null!=couponList&&couponList.size()>position){
					couponList.remove(position);
					myCouponListAdapter.notifyDataSetChanged();
				}
			};
		});
		//coupon列表的下拉刷新与上拉加载
		listView.setScrollingWhileRefreshingEnabled(true);
		listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				isLoading = true;
				pageIndex = 0;
				initData();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				//增加下拉加载
				isLoading = true;
				isPullUp = true;
				++pageIndex;
				initData();
			}
		});
		listView.getRefreshableView().setOnItemLongClickListener(this);
		listView.setOnItemClickListener(this);
	}
	
	/**
	 * @author tony
	 * 获取MyCoupon列表数据任务
	 */
	class GetMyCouponList extends BaseNeedReLoginTask{

		@Override
		protected void onPreExecute() {
			if(!isLoading){
				if(couponList.size()==0){
					showLoadingLayout(haveDataPage);
				}/*else{
					
//					progressLoad.setVisibility(View.VISIBLE);
				}*/
				
			}
//				showWaitingDialog();
				
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(Void... params) {
			// 调用接口获取服务端数据
			try {
				coupons = ProviderFactory.createCouponServiceProvider().FindCustomerCoupons(ActivityUtil.getCustomerID(), 1, 1, new String[]{"NotUsed"}, pageIndex, pageSize,
						ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(isAdded()){
				if(isLoading){
					isLoading =false;
					listView.onRefreshComplete();
				}
//				hideWaitingDialog();
				hideAllLayout();
//				progressLoad.setVisibility(View.GONE);
				
				if("0".equals(result)){
					if(coupons!=null && coupons.size()>0){
						//有数据
						if(!isPullUp){
							couponList.clear();
						}else{
							isPullUp = false;
						}
						couponList.addAll(coupons);
						if(coupons.size()<pageSize){
							//没有更多数据了，禁用上拉加载
							listView.setMode(Mode.PULL_FROM_START);
						}else{
							listView.setMode(Mode.BOTH);
						}
					}else{
//						AlertToast.alert(getActivity(), R.string.no_more_datas);
						if(pageIndex==0 && !isPullUp){
							couponList.clear();
						}
					}
					if(couponList.size()>0){
						hideAllLayout(haveDataPage);
//						progressLoad.setVisibility(View.GONE);
						myCouponListAdapter.notifyDataSetChanged();
					}else{
						//没有数据
						showEmptyLayout(haveDataPage, R.string.my_coupon_no_coupon, R.drawable.my_coupon_no_coupon);
					}
				}else if(!isRelogin){
					if(pageIndex==0&&(TextUtils.equals(ServerConstant.ReturnCode.
							VALIDATOR_UNKONW_ERROR, result)||TextUtils.equals(ServerConstant.ReturnCode.
									CLIENT_NET_UN_AVAILABLE, result))){
						if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
							showErrorLayout(haveDataPage, R.string.internet_error,
									R.string.internet_suggest, R.drawable.no_internet);
						}else{
							showErrorLayout(haveDataPage, R.string.server_busy,
									R.string.server_suggest, R.drawable.no_internet);
						}
						retryBtn.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								initData();
							}
						});
					}else{
						listView.onRefreshComplete();
						pageIndex--;
						listView.setMode(Mode.BOTH);
						AlertToast.alert(getActivity(),
								ServerConstant.ReturnCode.MESSAGEMAP
										.get(result));
					}
				}
				
			}
		}
		@Override
		protected Context setContext() {
			return getActivity();
		}
		@Override
		protected BaseNeedReLoginTask setTask() {
			return new GetMyCouponList();
		}
		
	}
	
	/**
	 * @author hf
	 * 删除用户Coupon
	 */
	class DeleteUserCoupon extends BaseNeedReLoginTask{

		private String couponCode;
		private int position;
		public DeleteUserCoupon(String couponCode,int position){
			this.couponCode = couponCode;
			this.position=position;
		}
		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(null);
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(Void... params) {
			try {
				ProviderFactory.createCouponServiceProvider().DeleteUserCoupon(ActivityUtil.getCustomerID(), couponCode,
						ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(isAdded()){
				hideAllLayout(haveDataPage);
//				hideWaitingDialog();
				if("0".equals(result)){
					if(couponList.size()==0){
						showEmptyLayout(haveDataPage, R.string.my_coupon_no_coupon, R.drawable.my_coupon_no_coupon);
						return;
					}
					if(couponList.size()>position){
						couponList.remove(position);
						myCouponListAdapter.notifyDataSetChanged();
					}
//					AlertToast.alert(getActivity(),
//							R.string.get_coupon_successed);
					if(couponList.size()<=0){
						isLoading = false;
						pageIndex = 0;
						initData();
					}
					
				}else{
					if(!isRelogin){
						AlertToast.alert(getActivity(),
								ServerConstant.ReturnCode.MESSAGEMAP
								.get(result));
					}
				}
			}
		}
		@Override
		protected Context setContext() {
			return getActivity();
		}
		@Override
		protected BaseNeedReLoginTask setTask() {
			return new DeleteUserCoupon(couponCode, position);
		}
		
	}
	
	
	/**
	 * 获取Coupon对应活动信息
	 * @author huangfei
	 *
	 */
	class FindCouponActiveInfo extends AsyncTask<Void, Void, String>{
		private CouponActiveModel couponActiveModel;
		private String couponCode;
		public FindCouponActiveInfo(String couponCode){
			this.couponCode = couponCode;
		}
		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(null);
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(Void... params) {
			try {
				couponActiveModel=ProviderFactory.createCouponServiceProvider().FindDiscountProducts(couponCode, 20,0, 0,"d=Popularity",
						ActivityUtil.getCustomerID(),OnekeyFilterLocalUtil.getFilterState(getActivity()),OnekeyFilterLocalUtil.getLocalCategoryIds(getActivity()));
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}
		@Override
		protected void onPostExecute(String result) {
			if(isAdded()){
//				hideWaitingDialog();
				hideAllLayout(haveDataPage);
				if("0".equals(result)){
					if(null!=couponActiveModel){
						boolean isWholeSite=couponActiveModel.isIsWholeSite();
						Logger.i("MyCouponFragment", isWholeSite+"");
						Intent intent=new Intent();
						if(couponActiveModel.isIsMvp()){//针对MVP的Coupon
							intent.setClass(getActivity(), ProductListActivity.class);
							intent.putExtra(Constant.PRODUCTLIST_TYPE,Constant.TYPE_MVP24HRS );
							intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_HOME);
							intent.putExtra(Constant.PRODUCT_TITLE, "MVP 24hrs");
							startActivity(intent);
							return;
						}
						if(!isWholeSite){
							int currencyCategoryId=couponActiveModel.getCurrencyCategoryId();
							List<CatelogModel> cates=couponActiveModel.getCategories();
							List<ProductModel> productLists=couponActiveModel.getProducts();
							Logger.i("MyCouponFragment", currencyCategoryId+" "+cates+" "+productLists);
							if(null!=productLists){
								if(currencyCategoryId==0){
									intent.setClass(getActivity(), ProductListActivity.class);
									intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_COUPON);
								}else{
									if(null==cates){
										return;
									}
									if(cates.size()==1){
										intent.setClass(getActivity(), ProductListActivity.class);
										intent.putExtra("catalogId", cates.get(0).getBrowseID());
										intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_COUPON);
										intent.putExtra(Constant.PRODUCT_TITLE, cates.get(0).getShortName());
									}else{
										intent.setClass(getActivity(), LandingPageActivity.class);
										ArrayList<CatelogModel> catelist = (ArrayList<CatelogModel>) cates;
										intent.putParcelableArrayListExtra("categorylist", catelist);
									}
								}
								ArrayList<ProductModel> prductlist = (ArrayList<ProductModel>) productLists;
								intent.putParcelableArrayListExtra("productlist", prductlist);
								intent.putExtra("CouponCode", couponCode);
								intent.putExtra("CurrencyCode", couponActiveModel.getCurrencyCode());
								intent.putExtra("CurrencyCodeStr", couponActiveModel.getCurrencyCodeStr());
								startActivity(intent);
							}
							
						}else{
							intent.setClass(getActivity(), HomeActivity.class);
							intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
									getString(HomeActivity.titleArray[0]));
							startActivity(intent);
						}
					}
				}else{
					AlertToast.alert(getActivity(),
								ServerConstant.ReturnCode.MESSAGEMAP
										.get(result));
				}
			}
			super.onPostExecute(result);
		}
		
	}
	
	/**
	 * 删除Coupon 对话框
	 * @param position
	 * @param couponCode
	 */
	public void showDeleteDialog(final int position,final String couponCode) {
		new AlertDialog.Builder(getActivity())
				.setTitle(R.string.delete)
				.setCancelable(true)
				.setMessage(R.string.user_wish_confirm_del)
				.setPositiveButton(R.string.btn_title_ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								new DeleteUserCoupon(couponCode, position).execute();
							}
						})
				.setNegativeButton(R.string.btn_title_cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).create().show();
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0,  View view, int position, long id) {
		Logger.i("MyCouponFragment", " onItemLongClick: "+position);
		
		if(couponList.size()<=position-1){
			return true;
		}
		final CouponModel coupon = (CouponModel)couponList.get(position - 1);
		if(null==coupon){
			return true;
		}
		showDeleteDialog(position-1, coupon.getCouponCode());
		return true;
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		if(couponList.size()<=position-1){
			return;
		}
		CouponModel couponModel=couponList.get(position-1);
		if(null!=couponModel){
			AsyncTaskUtil.executeTask(new FindCouponActiveInfo(couponModel.getCouponCode()));
		}
	}
}
